<template>
  <div class="master-box">
    <el-button
      v-if="!manageVisible"
      class="add"
      type="primary"
      @click="addMaster"
      >新增</el-button
    >
    <el-tabs v-model="activeName">
      <el-tab-pane label="金牌大师" name="list" style="margin-top: 20px;">
        <el-table :data="masterlist" stripe border>
          <el-table-column label="排序" width="180" align="center">
            <template slot-scope="scope">
              <el-input
                class="input-index"
                type="number"
                v-model="scope.row.show_order"
                @blur="changeOrder(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="大师名称" align="center">
          </el-table-column>
          <el-table-column label="首页展示" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_index_show"
                active-color="#13ce66"
                active-value="1"
                inactive-value="2"
                @change="(value) => changeExhibition(value, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" @click="editMaster(scope.row.id)"
                >编辑</el-button
              >
              <el-button type="danger" @click="deleteMaster(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane v-if="manageVisible" label="工作室管理" name="manage">
        <el-form
          :model="masterinfo"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="大师名称:" prop="name">
            <el-input v-model="masterinfo.name"></el-input>
          </el-form-item>

          <el-form-item label="大师头像:" prop="profile_photo">
            <el-upload
              :class="masterinfo.profile_photo == '' ? 'nodisable' : 'disable'"
              action="#"
              :auto-upload="false"
              list-type="picture-card"
              :on-change="(file, filelist) => uploadSuccess(file, filelist, 0)"
              :before-remove="(file, filelist) => removeFile(file, filelist, 0)"
              :limit="1"
              :file-list="list1"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="messages">
              <div>1、图片格式：jpg，png；</div>
              <div>2、长宽比例1：1；</div>
              <div>3、图片大小不超过2M；</div>
            </div>
          </el-form-item>

          <el-form-item label="可咨询时间:" prop="timeslot">
            <el-time-picker
              is-range
              format="HH:mm"
              value-format="HH:mm"
              v-model="masterinfo.timeslot"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            >
            </el-time-picker>
          </el-form-item>

          <el-form-item label="联系方式:" prop="mobile">
            <el-input v-model="masterinfo.mobile" placeholder="请输入">
            </el-input>
          </el-form-item>

          <el-form-item label="擅长品牌:" prop="brands">
            <el-tag
              size="medium"
              v-for="tag in masterinfo.brands"
              :key="tag.brand_id"
              closable
              @close="closeTag(tag)"
            >
              {{ tag.brand_name }}
            </el-tag>
            <el-select v-model="brand">
              <el-option
                v-for="item in brandlist"
                :key="item.brand_id"
                :value="item.brand_id"
                :label="item.brand_name"
                ><div @click="addBrand(item)">
                  {{ item.brand_name }}
                </div></el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item label="照片墙:" class="wall">
            <el-upload
              action="#"
              :auto-upload="false"
              list-type="picture-card"
              :on-change="(file, filelist) => uploadSuccess(file, filelist, 1)"
              :before-remove="(file, filelist) => removeFile(file, filelist, 1)"
              :file-list="list2"
              ><i class="el-icon-plus avatar-uploader-icon"></i
            ></el-upload>
            <div class="tit">
              图片格式：jpg，png；长宽比例4:3；图片大小不超过5M；
            </div>
          </el-form-item>
          <el-form-item label="用车小课堂:">
            <div class="video-box">
              <div
                class="video-list"
                v-for="item in masterinfo.car_use_class"
                :key="item.id"
              >
                <img :src="item.image_url" />
                <center class="video-title">{{item.title}}</center>
                <div>
                  <i class="el-icon-delete" @click="deleteVideo(item)"></i>
                </div>
              </div>

              <div class="videos" @click="showDialog">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="工作室简介:" prop="studio_desc">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 4 }"
              placeholder="请输入内容"
              v-model="masterinfo.studio_desc"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit">保存</el-button>
          </el-form-item>
        </el-form>

        <el-dialog title="视频上传" :visible.sync="videoVisible" width="40%">
          <el-form
            :model="videoform"
            :rules="videorules"
            ref="videoforms"
            label-width="100px"
          >
            <el-form-item label="视频标题:" prop="videoTitle">
              <el-input
                v-model="videoform.videoTitle"
                placeholder="请输入标题名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="视频路径:" prop="videoLink">
              <el-input
                v-model="videoform.videoLink"
                placeholder="视频路径从精彩视频中复制相应链接即可"
              ></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="videoVisible = false">取 消</el-button>
            <el-button type="primary" @click="addVideo">确 定</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeName: "list",
      masterlist: [],
      masterinfo: {
        name: "", //名称
        profile_photo: "", //头像
        timeslot: ["06:00", "20:00"], //咨询时间
        mobile: "",
        brands: [], //擅长品牌
        photo_wall: [], //照片墙
        car_use_class: [], //用车课堂
        studio_desc: "", //工作室简介
      },
      rules: {
        name: [{ required: true, message: "请输入大师名称", trigger: "blur" }],
        timeslot: [
          { required: true, message: "请选择咨询时间", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请填写联系方式", trigger: "blur" },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "手机号格式有误！",
            trigger: "blur",
          },
        ],
        brands: [
          { required: true, message: "请选择擅长品牌", trigger: "blur" },
        ],
        profile_photo: [
          { required: true, message: "请输上传大师头像", trigger: "blur" },
        ],
        studio_desc: [
          { required: true, message: "请填写工作室简介", trigger: "blur" },
        ],
      },
      brandlist: [],
      brand: "",
      videoVisible: false,
      videoList: [],
      videoform: {
        videoTitle: "",
        videoLink: "",
      },
      videorules: {
        videoTitle: [
          { required: true, message: "请输入标题", trigger: "blur" },
        ],
        videoLink: [
          { required: true, message: "请输入视频路径", trigger: "blur" },
        ],
      },
      edit: false,
      editId: "",
      list1: [],
      list2: [],
      list3: [],
    };
  },
  computed: {
    manageVisible() {
      if (this.activeName == "manage") {
        return true;
      } else {
        this.reset();
        return false;
      }
    },
  },
  created() {
    this.getList();
    this.getBrandList();
  },
  methods: {
    //获取大师列表
    getList() {
      this.$http
        .post("/admin/masterStudio/index.php?act=master&op=list")
        .then((res) => {
          if (res.code == 1) {
            this.masterlist = res.data;
          }
        });
    },
    // 获取品牌列表
    getBrandList() {
      this.$http
        .post("/admin/store/index.php?act=getBrand&op=selectBrand")
        .then((res) => {
          this.brandlist = res;
        });
    },
    //修改大师排序
    changeOrder(item) {
      const data = {
        id: item.id,
        show_order_num: item.show_order,
      };
      this.$http
        .post("/admin/masterStudio/index.php?act=master&op=editShowOrder", data)
        .then((res) => {
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.getList();
          } else {
            this.$message.warning(res.msg);
          }
        });
      this.getList();
    },
    // 更改首页展示
    changeExhibition(val, item) {
      const data = {
        id: item.id,
        index_show: val == "1" ? "show" : "unshow",
      };
      this.$http
        .post(
          "/admin/masterStudio/index.php?act=master&op=editIndexShowState",
          data
        )
        .then((res) => {
          if (res.code == 1) {
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    // 添加大师信息
    addMaster() {
      this.activeName = "manage";
      this.edit = false;
    },
    // 编辑大师信息
    editMaster(id) {
      this.activeName = "manage";
      this.editId = id;
      this.edit = true;
      this.$http
        .post("/admin/masterStudio/index.php?act=master&op=detail", { id })
        .then((res) => {
          if (res.code == 1) {
            this.masterinfo.name = res.data.name;
            this.masterinfo.profile_photo = res.data.profile_photo;
            this.masterinfo.timeslot = [
              res.data.work_start_time,
              res.data.work_end_time,
            ];
            this.masterinfo.photo_wall = res.data.photo_wall;
            this.masterinfo.mobile = res.data.mobile;
            res.data.photo_wall_info &&
              res.data.photo_wall_info.map((v) => {
                let i = {
                  name: "",
                  url: v,
                };
                this.list2.push(i);
              });
            let arr = [];
            res.data.brand_info &&
              res.data.brand_info.map((v) => {
                let i = {
                  brand_id: v.brand_id,
                  brand_name: v.brand_name,
                };
                arr.push(i);
              });
            this.masterinfo.brands = arr;
            res.data.video_info &&
              res.data.video_info.map((v) => {
                let j = {
                  name: "",
                  url: v.image_url,
                };
                this.list3.push(j);
              });
            this.list1 = [{ name: "", url: res.data.profile_photo_show }];
            this.masterinfo.car_use_class = res.data.video_info;
            this.masterinfo.studio_desc = res.data.studio_desc;
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    // 删除大师
    deleteMaster(id) {
      this.$confirm("确认删除该大师吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .post("/admin/masterStudio/index.php?act=master&op=delMaster", {
              id,
            })
            .then((res) => {
              if (res.code == 1) {
                this.$message.success(res.msg);
                this.getList();
              } else {
                this.$message.error(res.msg);
              }
            });
        })
        .catch((_) => {});
    },

    // 上传
    uploadSuccess(file, filelist, key) {
      const isJPG =
        file.raw.type == "image/jpeg" || file.raw.type == "image/png";
      var isLt2M;
      if (key == 0) {
        isLt2M = file.raw.size / 1024 / 1024 < 2;
      } else if (key == 1) {
        isLt2M = file.raw.size / 1024 / 1024 < 5;
      }

      if (!isJPG) {
        this.$message.warning("上传头像图片只能是 JPG或PNG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.warning(
          `上传头像图片大小不能超过 ${key == 0 ? "2" : "5"}MB!`
        );
        return;
      }
      let data = new FormData();
      data.append("file_info", file.raw);
      this.$http
        .post("/admin/masterStudio/index.php?act=master&op=uploadFiles", data)
        .then((res) => {
          if (res.code == 1) {
            switch (key) {
              case 0:
                this.masterinfo.profile_photo = res.data;
                break;
              case 1:
                if(this.masterinfo.photo_wall == null) this.masterinfo.photo_wall = []
                this.masterinfo.photo_wall.push(res.data);
                break;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    removeFile(file, filelist, key) {
      let data = new FormData();
      data.append("file_info", file.raw);
      this.$http
        .post("/admin/masterStudio/index.php?act=master&op=uploadFiles", data)
        .then((res) => {
          if (res.code == 1) {
            switch (key) {
              case 0:
                this.masterinfo.profile_photo = [];
                break;
              case 1:
                this.masterinfo.photo_wall.splice(
                  this.masterinfo.photo_wall.indexOf(res.data),
                  1
                );
                break;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    // 添加擅长品牌
    addBrand(item) {
      if (this.masterinfo.brands.indexOf(item) == -1) {
        this.masterinfo.brands.push(item);
      } else {
        return;
      }
    },
    showDialog() {
      this.videoVisible = true;
    },
    addVideo() {
      this.$refs["videoforms"].validate((valid) => {
        if (valid) {
          const data = { path: this.videoform.videoLink.trim() };
          this.$http
            .post(
              "/admin/masterStudio/index.php?act=master&op=getVideoImg",
              data
            )
            .then((res) => {
              if (res.code == 1) {
                if (res.data == null) {
                } else {
                  let l = this.masterinfo.car_use_class.filter(
                    (v) => v.id == res.data.id
                  ).length;
                  if (l >= 1) {
                    this.$message.warning("此视频已被添加!");
                  } else {
                    let item = { ...res.data };
                    let date = new Date();
                    let y = date.getFullYear();
                    let m =
                      String(date.getMonth() + 1).length == 2
                        ? date.getMonth() + 1
                        : "0" + date.getMonth() + 1;
                    let d =
                      date.getDay().length == 2
                        ? date.getDay()
                        : "0" + date.getDay();
                    item.date = y + "-" + m + "-" + d;
                    item.title = this.videoform.videoTitle;
                    item.video_link = this.videoform.videoLink;
                    this.masterinfo.car_use_class.push(item);
                  }
                }
                this.videoform = {
                  videoTitle: "",
                  videoLink: "",
                };
                this.videoVisible = false;
              } else {
                this.$message.warning(res.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    deleteVideo(item) {
      this.masterinfo.car_use_class.splice(
        this.masterinfo.car_use_class.indexOf(item),
        1
      );
    },
    // 删除擅长品牌
    closeTag(tag) {
      this.masterinfo.brands.splice(this.masterinfo.brands.indexOf(tag), 1);
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let brands = [];
          this.masterinfo.brands.map((v) => {
            let i = { brand_id: v.brand_id, brand_name: v.brand_name };
            brands.push(i);
          });
          let data = {
            brands: JSON.stringify(brands),
            name: this.masterinfo.name,
            work_start_time:
              this.masterinfo.timeslot[0].length > 5
                ? this.masterinfo.timeslot[0].substring(
                    0,
                    this.masterinfo.timeslot[0].length - 3
                  )
                : this.masterinfo.timeslot[0],
            work_end_time:
              this.masterinfo.timeslot[1].length > 5
                ? this.masterinfo.timeslot[1].substring(
                    0,
                    this.masterinfo.timeslot[1].length - 3
                  )
                : this.masterinfo.timeslot[1],
            profile_photo: this.masterinfo.profile_photo,
            studio_desc: this.masterinfo.studio_desc,
          };
          if (this.masterinfo.photo_wall!= null && this.masterinfo.photo_wall.length > 0) {
            data.photo_wall = this.masterinfo.photo_wall;
          }
          let car_arr = [];
          this.masterinfo.car_use_class != null && this.masterinfo.car_use_class.map((v) => {
            let c = {
              title: v.title,
              video_link: v.video_link,
              date: v.date,
              image_url: v.image_url,
            };
            car_arr.push(c);
          });
          data.car_use_class = JSON.stringify(car_arr);
          data.mobile = this.masterinfo.mobile;
          if (this.edit) data.id = this.editId;
          this.$http
            .post("/admin/masterStudio/index.php?act=master&op=save", data)
            .then((res) => {
              if (res.code == 1) {
                this.$message.success(res.msg);
                this.activeName = "list";
                this.getList();
              } else {
                this.$message.warning(res.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.activeName = "list";
    },
    reset() {
      this.masterinfo = {
        name: "", //名称
        profile_photo: "", //头像
        timeslot: ["06:00", "20:00"], //咨询时间
        mobile: "",
        brands: [], //擅长品牌
        photo_wall: [], //照片墙
        car_use_class: [], //用车课堂
        studio_desc: "", //工作室简介
      };
      this.list1 = [];
      this.list2 = [];
      this.list3 = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.master-box {
  position: relative;
  .add {
    position: absolute;
    right: 0;
    z-index: 99;
  }
  .input-index {
    width: 50px;
    text-align: center;
  }
  /deep/ input::-webkit-outer-spin-button,
  /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  /deep/ input[type="number"] {
    -moz-appearance: textfield;
  }
  .el-form {
    margin-top: 15px;
    .wall {
      margin-bottom: 40px;
    }
    .el-form-item {
      width: 500px;
      .el-date-editor {
        width: 100%;
      }
      .el-upload {
        width: 100px;
        height: 100px;
      }
      .tit {
        margin-top: 5px;
        line-height: 24px;
        color: #ccc;
      }
      .el-form-item__content {
        position: relative;
        .messages {
          position: absolute;
          right: 40px;
          top: 25px;
          div {
            line-height: 24px;
            color: #ccc;
          }
        }
      }
      .el-tag {
        margin-right: 10px;
        margin-bottom: 10px;
      }
      .el-select {
        width: 140px;
      }
      .videos {
        width: 148px;
        height: 148px;
        background-color: #fbfdff;
        border: 1px dashed #ccc;
        border-radius: 6px;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        .el-icon-plus {
          font-size: 28px;
          color: #8c939d;
        }
      }
      .videos:hover {
        border-color: #409eff;
      }
      .video-list {
        width: 148px;
        height: 148px;
        border-radius: 6px;
        margin-right: 20px;
        position: relative;
        // display: flex;
        // flex-direction: row;
        margin-bottom: 40px;
        img,
        div {
          width: 100%;
          height: 100%;
          border-radius: 6px;
          .el-icon-delete {
            font-size: 20px;
            color: #fff;
          }
        }
        div {
          z-index: -1;
        }
        .video-title {
          width: 100%;
          position: absolute;
          bottom: -30px;
          padding: 0 7px;
          color: #ccc;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .video-list:hover {
        div {
          z-index: 9;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: rgba(0, 0, 0, 0.5);
          .el-icon-delete {
            cursor: pointer;
          }
        }
      }
      .video-box {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }
      .edit-img {
        width: 148px;
        height: 148px;
        border-radius: 6px;
      }
    }
  }
  .disable /deep/.el-upload--picture-card {
    display: none;
  }
  .nodisable /deep/.el-upload--picture-card {
    display: inline-block;
    width: 148px;
    height: 148px;
  }
}
</style>
